<?php

namespace app\user\controller\user;

use app\common\controller\Backend;
use app\common\controller\Userend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 导入题目
 *
 * @icon fa fa-circle-o
 */
class Importquestion extends Userend
{

    /**
     * Importquestion模型对象
     * @var \app\admin\model\Importquestion
     */
    protected $model = null;

    /**
     * Questioncategory模型对象
     * @var \app\admin\model\Questioncategory
     */
    protected $questioncategoryModel = null;

    /**
     * 数据限制字段
     */
    protected $dataLimitField = 'create_uid';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Importquestion;
        $this->questioncategoryModel = new \app\admin\model\Questioncategory;
    }

    /**
     * 添加
     */
    public function add()
    {
        // 请求参数
        $course_id = $this->request->param('ids', 0);
        $extend_id = $this->request->param('extend_id', 0);
        if (!$course_id) {
            $this->error('请求参数不正确');
        }

        // 查询信息
        $courseInfo = \app\common\model\Course::get($course_id);
        if (!$courseInfo) {
            $this->error('查询课程信息失败');
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    if (empty($params['name'])) {
                        $this->error('请填写试卷名称');
                    }
                    if (empty($params['attachment'])) {
                        $this->error('请上传试卷文件');
                    }
                    if (empty($params['extend_id'])) {
                        $this->error('请选择导入分类');
                    }

                    // 检查分类
                    $extendInfo = $this->questioncategoryModel->find($params['extend_id']);
                    if (!$extendInfo) {
                        $this->error('导入分类不存在');
                    }

                    // 填充信息
                    $params['course_id'] = $courseInfo['id'];
                    $params['course_name'] = $courseInfo['name'];
                    $params['extend_id'] = $extendInfo['id'];
                    $params['extend_name'] = $extendInfo['name'];
                    $params['create_time'] = time();
                    $params['update_time'] = time();
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("extend_id", $extend_id);
        $this->view->assign("courseInfo", $courseInfo);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($row['status'] != 3) {
            $this->error(__('已完成导入任务不能重新导入'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }

                    // 检查数据
                    if (empty($params['name'])) {
                        $this->error('请填写试卷名称');
                    }
                    if (empty($params['attachment'])) {
                        $this->error('请上传试卷文件');
                    }
                    if (empty($params['extend_id'])) {
                        $this->error('请选择导入分类');
                    }

                    // 检查分类
                    $extendInfo = $this->questioncategoryModel->find($params['extend_id']);
                    if (!$extendInfo) {
                        $this->error('导入分类不存在');
                    }

                    $params['extend_id'] = $extendInfo['id'];
                    $params['extend_name'] = $extendInfo['name'];
                    $params['update_time'] = time();
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

}
